package com.jieli.stream.dv.running2.ui.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

import com.jieli.lib.dv.control.DeviceClient;
import com.jieli.lib.dv.control.connect.listener.OnConnectStateListener;
import com.jieli.lib.dv.control.connect.response.SendResponse;
import com.jieli.lib.dv.control.json.bean.NotifyInfo;
import com.jieli.lib.dv.control.receiver.listener.OnNotifyListener;
import com.jieli.lib.dv.control.utils.Code;
import com.jieli.lib.dv.control.utils.Constants;
import com.jieli.lib.dv.control.utils.Topic;
import com.jieli.lib.dv.control.utils.TopicKey;
import com.jieli.lib.dv.control.utils.TopicParam;
import com.jieli.stream.dv.running2.bean.FileInfo;
import com.jieli.stream.dv.running2.task.ClearThumbTask;
import com.jieli.stream.dv.running2.task.DeviceDescription;
import com.jieli.stream.dv.running2.task.HeartbeatTask;
import com.jieli.stream.dv.running2.task.SDPServer;
import com.jieli.stream.dv.running2.ui.MainApplication;
import com.jieli.stream.dv.running2.util.AppUtils;
import com.jieli.stream.dv.running2.util.ClientManager;
import com.jieli.stream.dv.running2.util.Dbug;
import com.jieli.stream.dv.running2.util.IActions;
import com.jieli.stream.dv.running2.util.IConstant;
import com.jieli.stream.dv.running2.util.PreferencesHelper;
import com.jieli.stream.dv.running2.util.TimeFormate;
import com.jieli.stream.dv.running2.util.json.JSonManager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.jieli.lib.dv.control.utils.Constants.SEND_SUCCESS;

public class CommunicationService extends Service implements IConstant, IActions {
    private static final String tag = CommunicationService.class.getSimpleName();
    private HeartbeatTask mHeartbeatTask = null;
    private DeviceDescription loadDeviceDesTxt;
    private MainApplication mApplication;
    private SDPServer mLiveServer;
    private ClearThumbTask clearThumbTask;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //Dbug.i(tag, "=====CommunicationService==onCreate=====");
        ClientManager.getClient().registerNotifyListener(onNotifyResponse);
        ClientManager.getClient().registerConnectStateListener(connectStateListener);
        mApplication = MainApplication.getApplication();
//        if (MainApplication.isOpenLeakCanary) mApplication.getRefWatcher().watch(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            return START_STICKY;
        }
        int cmd = intent.getIntExtra(SERVICE_CMD, -1);
        Dbug.i(tag, "onStartCommand==========cmd=" + cmd);
        switch (cmd) {
            case SERVICE_CMD_CONNECT_CTP:
                String ip = intent.getStringExtra(KEY_CONNECT_IP);
                if(TextUtils.isEmpty(ip)){
                    ip = DEFAULT_DEV_IP;
                }
                if (!ClientManager.getClient().isConnected()) {
                    ClientManager.getClient().create(ip, CTP_TCP_PORT);
//                    ClientManager.getClient().create(ip, CTP_UDP_PORT);
                }
                break;
            case SERVICE_CMD_DISCONNECT_CTP:
                ClientManager.getClient().disconnect();
                break;

        }
        return START_STICKY;
    }

    private final OnNotifyListener onNotifyResponse = new OnNotifyListener() {

        @Override
        public void onNotify(NotifyInfo data) {
            if(data == null) return;
//            if (!Topic.KEEP_ALIVE.equals(data.getTopic()))Dbug.w(tag, "Device Notify=" + data);
            String topic = data.getTopic();
            if (TextUtils.isEmpty(topic)) return;
            Intent intent;
            if (data.getErrorType() != Code.ERROR_NONE) {
                Dbug.e(tag, "Topic " + data.getTopic() + ", error msg: "+Code.getCodeDescription(data.getErrorType()));
                if(Topic.APP_ACCESS.equals(topic)) {
                    intent = new Intent(ACTION_DEV_ACCESS);
                    intent.putExtra(KEY_ALLOW_ACCESS, false);
                    sendBroadcast(intent);
                } else if(Topic.CLOSE_PULL_RT_STREAM.equals(topic)){
                    mApplication.getDeviceSettingInfo().setExistRearView(false);
                    if (Code.ERROR_REAR_CAMERA_OFFLINE == data.getErrorType()) {
                        if(mApplication.getDeviceSettingInfo().getCameraType() == DeviceClient.CAMERA_REAR_VIEW){
                            PreferencesHelper.putBooleanValue(getApplicationContext(), AppUtils.getAutoRearCameraKey(mApplication.getUUID()), true);
                        }
                        mApplication.getDeviceSettingInfo().setCameraType(DeviceClient.CAMERA_FRONT_VIEW);
                    }
                }
                return;
            }
            switch (topic) {
                case Topic.KEEP_ALIVE_INTERVAL:
                    int interval = Integer.parseInt(data.getParams().get(TopicKey.TIMEOUT));
                    //start heartbeat task.
                    if (mHeartbeatTask == null) {
                        mHeartbeatTask = new HeartbeatTask(CommunicationService.this);
                        mHeartbeatTask.start();
                    }
                    Dbug.i(tag, "Timeout interval:" + interval);
                    mHeartbeatTask.setPeriodAndTimeout((interval/HeartbeatTask.DEFAULT_HEARTBEAT_TIMEOUT)
                            , HeartbeatTask.DEFAULT_HEARTBEAT_TIMEOUT);
                    break;
                case Topic.TF_STATUS:
                    Dbug.i(tag, "TF Card state:" + data.getParams().get(TopicKey.ONLINE));
                    if (TopicParam.TF_ONLINE.equals(data.getParams().get(TopicKey.ONLINE))) {
                        MainApplication.getApplication().setSdcardExist(true);
                    } else {
                        MainApplication.getApplication().setSdcardExist(false);
                    }
                    sendBroadcast(new Intent(ACTION_TF_STATUS));
                    break;
                case Topic.APP_ACCESS:
                    String date = TimeFormate.formatYMD_HMS(Calendar.getInstance().getTime());
                    ClientManager.getClient().tryToSyncDevDate(date, new SendResponse() {
                        @Override
                        public void onResponse(Integer code) {
                            if (code != SEND_SUCCESS) {
                                Dbug.e(tag, "Send failed");
                            }
                        }
                    });
                    intent = new Intent(ACTION_DEV_ACCESS);
                    intent.putExtra(KEY_ALLOW_ACCESS, true);
                    sendBroadcast(intent);
                    if(clearThumbTask == null){
                        clearThumbTask = new ClearThumbTask();
                        clearThumbTask.setOnClearThumbTaskListener(new ClearThumbTask.OnClearThumbTaskListener() {
                            @Override
                            public void onFinish() {
                                clearThumbTask = null;
                            }
                        });
                        clearThumbTask.start();
                    }
                    if (!MainApplication.getApplication().isUpgrading()) {
                        if (loadDeviceDesTxt == null) {
                            loadDeviceDesTxt = new DeviceDescription(CommunicationService.this);
                            loadDeviceDesTxt.start();
                        }
                    }
                    break;
                case Topic.DEVICE_UUID:
                    String devUUID = data.getParams().get(TopicKey.UUID);
                    if (!TextUtils.isEmpty(devUUID)) {
                        Dbug.i(tag, "device uuid :" + devUUID);
                        MainApplication.getApplication().setUUID(devUUID);
                    }
                    break;
                case Topic.KEEP_ALIVE:
                    if (mHeartbeatTask != null) {
                        mHeartbeatTask.resetTimeoutCount();
                    }
                    break;
                case Topic.VIDEO_CTRL:
                    String state = data.getParams().get(TopicKey.STATUS);
                    if (!TextUtils.isEmpty(state)) {
                        boolean isRecord = TopicParam.OPEN.equals(state);
                        if (isRecord) {
                            mApplication.getDeviceSettingInfo().setRecordState(STATUS_RECORDING);
                        } else {
                            mApplication.getDeviceSettingInfo().setRecordState(STATUS_NOT_RECORD);
                        }
                    }
                    break;
                case Topic.VIDEO_FINISH:
                    String state1 = data.getParams().get(TopicKey.STATUS);
                    if (!TextUtils.isEmpty(state1)) {
                        boolean isRecord = TopicParam.OPEN.equals(state1);
                        if (isRecord) {
                            mApplication.getDeviceSettingInfo().setRecordState(STATUS_RECORDING);
                        } else {
                            mApplication.getDeviceSettingInfo().setRecordState(STATUS_NOT_RECORD);
                        }
                    }
                    String desc = data.getParams().get(TopicKey.DESC);
                    if (!TextUtils.isEmpty(desc)) {
                        desc = desc.replaceAll("\\\\", "");
                        Dbug.w(tag, "-VIDEO_FINISH- desc = " + desc);
                        FileInfo fileInfo = JSonManager.parseFileInfo(desc);
                        if (fileInfo != null) {
                            List<FileInfo> totalList = JSonManager.getInstance().getInfoList();
                            if (totalList == null) {
                                totalList = new ArrayList<>();
                            }
                            int cameraType = DeviceClient.CAMERA_FRONT_VIEW;
                            if(CAMERA_TYPE_REAR.equals(fileInfo.getCameraType())){
                                cameraType = DeviceClient.CAMERA_REAR_VIEW;
                            }
                            if(cameraType == mApplication.getDeviceSettingInfo().getCameraType()) {
                                totalList.add(0, fileInfo);
                                JSonManager.convertJson(totalList);
                            }
                        }
                    } else Dbug.e(tag, "CMD:VIDEO_FINISH:desc is null");
                    break;
                case Topic.TF_CARD_CAPACITY:
                    if (null != data.getParams()) {
                        String left = data.getParams().get(TopicKey.LEFT);
                        String total = data.getParams().get(TopicKey.TOTAL);
                        int leftValue = 0;
                        int totalValue = 0;
                        try {
                            leftValue = Integer.valueOf(left);
                            totalValue = Integer.valueOf(total);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        mApplication.getDeviceSettingInfo().setLeftStorage(leftValue);
                        mApplication.getDeviceSettingInfo().setTotalStorage(totalValue);
                    }
                    break;
                case Topic.FORMAT_TF_CARD:
                    sendBroadcast(new Intent(ACTION_FORMAT_TF_CARD));
                    break;
                case Topic.VIDEO_MIC:
                    mApplication.getDeviceSettingInfo().setVideoMic("1".equals(data.getParams().get(TopicKey.MIC)));
                    break;
                case Topic.PHOTO_QUALITY:
                    String qua = data.getParams().get(TopicKey.QUA);
                    if (!TextUtils.isEmpty(qua) && TextUtils.isDigitsOnly(qua))
                        mApplication.getDeviceSettingInfo().setPhotoQualityIndex(Integer.valueOf(qua));
                    break;
                case Topic.LANGUAGE:
                    String lan = data.getParams().get(TopicKey.LAG);
                    if (!TextUtils.isEmpty(lan) && TextUtils.isDigitsOnly(lan)) {
                        String preIndex = PreferencesHelper.getSharedPreferences(getApplicationContext()).getString(KEY_APP_LANGUAGE_CODE, "-1");
                        if (!lan.equals(preIndex)) {
                            //Dbug.e(tag, "Language =" + lan + ", preIndex="+preIndex);
                            AppUtils.changeAppLanguage(getApplicationContext(), lan);
                            sendBroadcast(new Intent(IActions.ACTION_LANGUAAGE_CHANGE));
                            PreferencesHelper.putStringValue(getApplicationContext(), KEY_APP_LANGUAGE_CODE, lan);
                        } else Dbug.w(tag, "lan=" + lan + ", preIndex="+preIndex);
                    } else Dbug.w(tag, "lan=" + lan);
                    break;
                case Topic.GRA_SEN:
                    String gra = data.getParams().get(TopicKey.GRA);
                    if (!TextUtils.isEmpty(gra) && TextUtils.isDigitsOnly(gra))
                        mApplication.getDeviceSettingInfo().setGravitySensor(Integer.valueOf(gra));
                    break;
                case Topic.VIDEO_PAR_CAR:
                    mApplication.getDeviceSettingInfo().setVideoParCar("1".equals(data.getParams().get(TopicKey.PAR)));
                    break;
                case Topic.VIDEO_DATE:
                    mApplication.getDeviceSettingInfo().setVideoDate("1".equals(data.getParams().get(TopicKey.DAT)));
                    break;
                case Topic.DEVICE_KEY_SOUND:
                    mApplication.getDeviceSettingInfo().setKeyVoice("1".equals(data.getParams().get(TopicKey.KVO)));
                    break;
                case Topic.BATTERY_STATUS:
                    String level = data.getParams().get(TopicKey.LEVEL);
                    if (!TextUtils.isEmpty(level) && TextUtils.isDigitsOnly(level))
                        mApplication.getDeviceSettingInfo().setBatStatus(Integer.valueOf(level));
                    break;
                case Topic.LIGHT_FRE:
                    String frequency = data.getParams().get(TopicKey.FREQUENCY);
                    if (!TextUtils.isEmpty(frequency) && TextUtils.isDigitsOnly(frequency))
                        mApplication.getDeviceSettingInfo().setLightFrequece(Integer.valueOf(frequency));
                    break;
                case Topic.AUTO_SHUTDOWN:
                    String aff = data.getParams().get(TopicKey.AFF);
                    if (!TextUtils.isEmpty(aff) && TextUtils.isDigitsOnly(aff))
                        mApplication.getDeviceSettingInfo().setAutoShutdown(Integer.valueOf(aff));
                    break;
                case Topic.SCREEN_PRO:
                    String pro = data.getParams().get(TopicKey.PRO);
                    if (!TextUtils.isEmpty(pro) && TextUtils.isDigitsOnly(pro))
                        mApplication.getDeviceSettingInfo().setScreenOn(Integer.valueOf(pro));
                    break;
                case Topic.TV_MODE:
                    String tvm = data.getParams().get(TopicKey.TV_MODE);
                    if (!TextUtils.isEmpty(tvm) && TextUtils.isDigitsOnly(tvm))
                        mApplication.getDeviceSettingInfo().setTvMode(Integer.valueOf(tvm));
                    break;
                case Topic.DOUBLE_VIDEO:
                    mApplication.getDeviceSettingInfo().setDoubleVideo("1".equals(data.getParams().get(TopicKey.TWO)));
                    break;
                case Topic.VIDEO_LOOP:
                    String cyc = data.getParams().get(TopicKey.CYC);
                    if (!TextUtils.isEmpty(cyc) && TextUtils.isDigitsOnly(cyc))
                        mApplication.getDeviceSettingInfo().setVideoLoop(Integer.valueOf(cyc));
                    break;
                case Topic.VIDEO_WDR:
                    mApplication.getDeviceSettingInfo().setVideoWdr("1".equals(data.getParams().get(TopicKey.WDR)));
                    break;
                case Topic.VIDEO_EXP:
                    String exp = data.getParams().get(TopicKey.EXP);
                    if (!TextUtils.isEmpty(exp) && TextUtils.isDigitsOnly(exp))
                        mApplication.getDeviceSettingInfo().setVideoExp(Integer.valueOf(exp));
                    break;
                case Topic.MOVE_CHECK:
                    mApplication.getDeviceSettingInfo().setMoveCheck("1".equals(data.getParams().get(TopicKey.MOT)));
                    break;
                case Topic.VIDEO_INV:
                    String gap = data.getParams().get(TopicKey.GAP);
                    if (!TextUtils.isEmpty(gap) && TextUtils.isDigitsOnly(gap))
                        mApplication.getDeviceSettingInfo().setVideoInv(Integer.valueOf(gap));
                    break;
                case Topic.PHOTO_RESO:
                    String resolution = data.getParams().get(TopicKey.RESOLUTION);
                    if (!TextUtils.isEmpty(resolution) && TextUtils.isDigitsOnly(resolution))
                        mApplication.getDeviceSettingInfo().setPhotoReso(Integer.valueOf(resolution));
                    break;
                case Topic.SELF_TIMER:
                    String phm = data.getParams().get(TopicKey.PHM);
                    if (!TextUtils.isEmpty(phm) && TextUtils.isDigitsOnly(phm))
                        mApplication.getDeviceSettingInfo().setSelfTime(Integer.valueOf(phm));
                    break;
                case Topic.BURST_SHOT:
                    mApplication.getDeviceSettingInfo().setBurstShot("1".equals(data.getParams().get(TopicKey.CYT)));
                    break;
                case Topic.PHOTO_SHARPNESS:
                    String acu = data.getParams().get(TopicKey.ACU);
                    if (!TextUtils.isEmpty(acu) && TextUtils.isDigitsOnly(acu))
                        mApplication.getDeviceSettingInfo().setPhotoSharpness(Integer.valueOf(acu));
                    break;
                case Topic.PHOTO_ISO:
                    String iso = data.getParams().get(TopicKey.ISO);
                    if (!TextUtils.isEmpty(iso) && TextUtils.isDigitsOnly(iso))
                        mApplication.getDeviceSettingInfo().setPhotoIso(Integer.valueOf(iso));
                    break;
                case Topic.PHOTO_EXP:
                    String photoExp = data.getParams().get(TopicKey.EXP);
                    if (!TextUtils.isEmpty(photoExp) && TextUtils.isDigitsOnly(photoExp))
                        mApplication.getDeviceSettingInfo().setPhotoExp(Integer.valueOf(photoExp));
                    break;
                case Topic.ANTI_TREMOR:
                    mApplication.getDeviceSettingInfo().setAntiTremor(TopicParam.OPEN.equals(data.getParams().get(TopicKey.SOK)));
                    break;
                case Topic.PHOTO_DATE:
                    mApplication.getDeviceSettingInfo().setPhotoDate(TopicParam.OPEN.equals(data.getParams().get(TopicKey.DAT)));
                    break;
                case Topic.BOARD_VOICE:
                    mApplication.getDeviceSettingInfo().setOpenBootSound(TopicParam.OPEN.equals(data.getParams().get(TopicKey.BVO)));
                    break;
                case Topic.RT_TALK_CTL:
                    if (null != data.getParams()) {
                        boolean isRtVoiceOpen = TopicParam.OPEN.equals(data.getParams().get(TopicKey.STATUS));
                        mApplication.getDeviceSettingInfo().setRTVoice(isRtVoiceOpen);
                    }
                    break;
                case Topic.OPEN_FRONT_RTS:
                    mApplication.getDeviceSettingInfo().setCameraType(DeviceClient.CAMERA_FRONT_VIEW);
                    startSdpServer(data);
                    break;
                case Topic.OPEN_REAR_RTS:
                    mApplication.getDeviceSettingInfo().setCameraType(DeviceClient.CAMERA_REAR_VIEW);
                    startSdpServer(data);
                    break;
                case Topic.PULL_VIDEO_STATUS://后拉实时流状态检测
                    if (null != data.getParams()) {
                        Dbug.w(tag, " >>>> data : "+data.toString());
                        boolean isExistRearCamera = TopicParam.TF_ONLINE.equals(data.getParams().get(TopicKey.STATUS));
                        mApplication.getDeviceSettingInfo().setExistRearView(isExistRearCamera);
                    }
                    break;
                case Topic.VIDEO_PARAM:
                case Topic.PULL_VIDEO_PARAM:{
                    //Dbug.w(tag, "PULL_VIDEO_PARAM:"+data.toString());
                    cachePlaybackVideoParam(data);
                    break;
                }
                default:
                    break;
            }
        }
    };

    private OnConnectStateListener connectStateListener = new OnConnectStateListener() {
        @Override
        public void onStateChanged(Integer state) {
            switch (state) {
                case Constants.DEVICE_STATE_CONNECTED:
                    break;
                case Constants.DEVICE_STATE_CONNECTION_TIMEOUT:
                case Constants.DEVICE_STATE_EXCEPTION:
                case Constants.DEVICE_STATE_DISCONNECTED:
                case Constants.DEVICE_STATE_UNREADY:
                    if (mHeartbeatTask != null) {
                        Dbug.e(tag, "stop mHeartbeatTask");
                        if (mHeartbeatTask.isHeartbeatTaskRunning()) {
                            mHeartbeatTask.stopRunning();
                        }
                        mHeartbeatTask = null;
                    }
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        //Dbug.w(tag, "onDestroy=============");
        release();
        super.onDestroy();
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        //Dbug.w(tag, "onTaskRemoved=============");
        release();
        stopSelf();
        super.onTaskRemoved(rootIntent);
    }

    private void release() {
        Dbug.e(tag, "======= (( release )) =====");
        ClientManager.getClient().unregisterNotifyListener(onNotifyResponse);
        ClientManager.getClient().unregisterConnectStateListener(connectStateListener);
//        ClientManager.getClient().release();
        if(clearThumbTask != null){
            clearThumbTask.stopClear();
            clearThumbTask = null;
        }
        if (loadDeviceDesTxt != null) {
            loadDeviceDesTxt.interrupt();
            loadDeviceDesTxt = null;
        }
        if (mHeartbeatTask != null) {
            mHeartbeatTask.stopRunning();
            mHeartbeatTask = null;
        }
        stopSdpServer();
    }

    private void startSdpServer(NotifyInfo data) {
        if (null == data.getParams()) {
            Dbug.e(tag, "cachePlaybackVideoParam is null");
            return;
        }
        if (mLiveServer == null) {
            int frameRate = VIDEO_FRAME_RATE_DEFAULT;
            int sampleRate = AUDIO_SAMPLE_RATE_DEFAULT;
            int format = -1;
            String rtsFormat = data.getParams().get(TopicKey.FORMAT);
            String rtsFrameRate = data.getParams().get(TopicKey.FRAME_RATE);
            String rtsSampleRate = data.getParams().get(TopicKey.SAMPLE);
            if(!TextUtils.isEmpty(rtsSampleRate) && TextUtils.isDigitsOnly(rtsSampleRate)){
                sampleRate = Integer.valueOf(rtsSampleRate);
            }
            if(!TextUtils.isEmpty(rtsFrameRate) && TextUtils.isDigitsOnly(rtsFrameRate)){
                frameRate = Integer.valueOf(rtsFrameRate);
            }
            if(!TextUtils.isEmpty(rtsFormat) && TextUtils.isDigitsOnly(rtsFormat)){
                format = Integer.valueOf(rtsFormat);
            }
            mLiveServer = new SDPServer(SDP_PORT, format);
            mLiveServer.setFrameRate(frameRate);
            mLiveServer.setSampleRate(sampleRate);
            Dbug.i(tag, "format " + format +", frameRate=" + frameRate +", sampleRate=" + sampleRate);
            mLiveServer.setRtpVideoPort(RTP_VIDEO_PORT1);
            mLiveServer.setRtpAudioPort(RTP_AUDIO_PORT1);
            mLiveServer.start();
        }
    }

    private void stopSdpServer() {
        if (mLiveServer != null) {
            mLiveServer.stopRunning();
            mLiveServer = null;
        }
    }

    private void cachePlaybackVideoParam(NotifyInfo data) {
        if (null == data.getParams()) {
            Dbug.e(tag, "cachePlaybackVideoParam is null");
            return;
        }
        String strWidth = data.getParams().get(TopicKey.WIDTH);
        String strHeight = data.getParams().get(TopicKey.HEIGHT);
        String rearFormat = data.getParams().get(TopicKey.FORMAT);
        String strFrameRate = data.getParams().get(TopicKey.FRAME_RATE);
        String strSampleRate = data.getParams().get(TopicKey.SAMPLE);
        if (!TextUtils.isEmpty(strWidth) && TextUtils.isDigitsOnly(strWidth) &&
                !TextUtils.isEmpty(strHeight) && TextUtils.isDigitsOnly(strHeight)) {
            int width = Integer.valueOf(strWidth);
            int height = Integer.valueOf(strHeight);
            int resolutionLevel = AppUtils.adjustRtsResolution(width, height);
            if (Topic.VIDEO_PARAM.equals(data.getTopic())) {
                mApplication.getDeviceSettingInfo().setFrontRecordLevel(resolutionLevel);
                mApplication.getDeviceSettingInfo().setFrontLevel(resolutionLevel);
            } else {
                mApplication.getDeviceSettingInfo().setRearRecordLevel(resolutionLevel);
                mApplication.getDeviceSettingInfo().setRearLevel(resolutionLevel);
            }
        }
        if (!TextUtils.isEmpty(rearFormat) && TextUtils.isDigitsOnly(rearFormat)) {
            int format = DeviceClient.RTS_H264;
            try {
                format = Integer.valueOf(rearFormat);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (format == DeviceClient.RTS_JPEG) {
                if (Topic.VIDEO_PARAM.equals(data.getTopic())) {
                    mApplication.getDeviceSettingInfo().setFrontFormat(DeviceClient.RTS_JPEG);
                } else {
                    mApplication.getDeviceSettingInfo().setRearFormat(DeviceClient.RTS_JPEG);
                }
            } else {
                if (Topic.VIDEO_PARAM.equals(data.getTopic())) {
                    mApplication.getDeviceSettingInfo().setFrontFormat(DeviceClient.RTS_H264);
                } else {
                    mApplication.getDeviceSettingInfo().setRearFormat(DeviceClient.RTS_H264);
                }
            }
        }
        if(!TextUtils.isEmpty(strFrameRate) && TextUtils.isDigitsOnly(strFrameRate)){
            int frameRate = VIDEO_FRAME_RATE_DEFAULT;
            try {
                frameRate = Integer.valueOf(strFrameRate);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (Topic.VIDEO_PARAM.equals(data.getTopic())) {
                mApplication.getDeviceSettingInfo().setFrontRate(frameRate);
            } else {
                mApplication.getDeviceSettingInfo().setRearRate(frameRate);
            }
        }
        if(!TextUtils.isEmpty(strSampleRate) && TextUtils.isDigitsOnly(strSampleRate)){
            int sampleRate = AUDIO_SAMPLE_RATE_DEFAULT;
            try {
                sampleRate = Integer.valueOf(strSampleRate);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (Topic.VIDEO_PARAM.equals(data.getTopic())) {
                mApplication.getDeviceSettingInfo().setFrontSampleRate(sampleRate);
            } else {
                mApplication.getDeviceSettingInfo().setRearSampleRate(sampleRate);
            }
        }
    }
}
